package com.itheima.reggic.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggic.common.R;
import com.itheima.reggic.dto.SetmealDto;
import com.itheima.reggic.pojo.Category;
import com.itheima.reggic.pojo.Setmeal;
import com.itheima.reggic.service.CategoryService;
import com.itheima.reggic.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        log.info("查询套餐:{}", setmeal);
        if (setmeal == null || setmeal.getCategoryId() == null)
            return R.error("查询失败");

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getStatus, 1);
        queryWrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId());
        List<Setmeal> setmealList = setmealService.list(queryWrapper);

        return R.success(setmealList);

    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        Page<Setmeal> pageObj = new Page<>(page, pageSize);
        Page<SetmealDto> pageDto = new Page<>(page, pageSize);

        // 查询分类字段
        List<Category> list = categoryService.list();
        // 由于分类菜单的name是唯一的，所以可以查询出分类数据，然后将其组合为key-value形式
        // 可以减少数据库的请求次数
        HashMap<Long, String> categoryMap = new HashMap<>();
        list.forEach(category -> {
            categoryMap.put(category.getId(), category.getName());
        });

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);

        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageObj, queryWrapper);
        // 被拷贝的对象，需要拷贝的对象，忽略的属性(字段)
        BeanUtils.copyProperties(pageObj, pageDto, "records");

        // 定义最后结果集,由于pageDto.getRecords() 获取的集合是一个不可变的列表或只读列表，因此无法执行添加操作。
        // 所以转为ArrayList
        ArrayList<SetmealDto> dishDtoList = new ArrayList<>(pageDto.getRecords());

        // 遍历每一个菜品，查询他们的CategoryName，并赋值给DishDto
        pageObj.getRecords().forEach(dish -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(dish, setmealDto);
//            Category serviceById = categoryService.getById(setmealDto.getCategoryId());
            setmealDto.setCategoryName(categoryMap.get(setmealDto.getCategoryId()));
            dishDtoList.add(setmealDto);
        });
        // 将最后的结果集返回给pageDto
        pageDto.setRecords(dishDtoList);
        return R.success(pageDto);

    }

    @PostMapping
    public R<String> add(@RequestBody SetmealDto setmealDto) {
        log.info("套餐新增信息:{}", setmealDto);
        setmealService.addWithDish(setmealDto);
        return R.success("保存成功!");
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除的数据:{}", ids);


        setmealService.deleteWithDish(ids);


        return R.success("删除成功!");
    }

    @PostMapping("/status/{status}")
    public R<String> changeStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("删除的数据:{}", ids);
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            boolean update = setmealService.updateById(setmeal);

        }
        return R.success("修改成功!");
    }

}
